package com.fulihui.systemcore;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import org.near.toolkit.common.StringUtil;
import org.near.toolkit.security.codec.AESCoder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;
import com.fulihui.systemcore.dal.dataobj.PhoneRegLoc;
import com.fulihui.systemcore.dal.mapper.PhoneRegLocMapper;
import com.fulihui.systemcore.dto.PosCityDTO;
import com.fulihui.systemcore.repository.CityModuleRepository;

/**
 * @author Willard.Hu on 2016/11/28 0028.
 */
public class PhoneRegLocSpider {

    private PhoneRegLocMapper phoneRegLocMapper;

    private CityModuleRepository cityModuleRepository;

    private static final int[] suits = {130, 131, 132, 133, 134, 135, 136, 137, 138, 139,
            150, 151, 152, 153, 155, 156, 157, 158, 159, 180, 181, 182, 183, 184, 185, 186,
            187, 188, 189, 145, 147, 170, 171, 173, 175, 176, 177, 178};

    static final int[] suits_run = {186,
            187, 188, 189, 145, 147, 170, 171, 173, 175, 176, 177, 178};

    public static void main(String[] args) {
        PhoneRegLocSpider spider = new PhoneRegLocSpider();
        spider.init();
        for (int suit : suits_run) {
            for (int i = 0; i < 10000; i++) {
                // 断点开始
                if (suit == 184 && i < 5934) {
                    i = 5934;
                }
                try {
                    int num = suit * 10000 + i;
                    String jsonResult = spider.queryAPI(num);
                    spider.writeObject(JSONObject.parseObject(jsonResult), suit);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        TimeUnit.MILLISECONDS.sleep(150);
                    } catch (InterruptedException ignore) {
                    }
                }
            }
        }
    }

    void init() {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "classpath:spring/componentscan-context.xml",
                "classpath:spring/test-datasource-context.xml");
        phoneRegLocMapper = context.getBean(PhoneRegLocMapper.class);
        cityModuleRepository = context.getBean(CityModuleRepository.class);
    }

    String queryAPI(int num) {
        String result;
        StringBuilder sbf = new StringBuilder();
        String httpUrl = "http://apis.baidu.com/showapi_open_bus/mobile/find?num=" + num;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey", "74953f53b61e5101475e8b11289fb41d");
            connection.connect();
            InputStream is = connection.getInputStream();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
                String strRead;
                while ((strRead = reader.readLine()) != null) {
                    sbf.append(strRead);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    void writeObject(JSONObject jsonObject, int suit) {
        if (jsonObject.getInteger("showapi_res_code") != 0) {
            System.err.println(jsonObject);
        }
        JSONObject body = jsonObject.getJSONObject("showapi_res_body");
        PhoneRegLoc phoneRegLoc = new PhoneRegLoc();
        Integer num = body.getInteger("num");
        if (num == null) {
            return;
        }
        phoneRegLoc.setPrefix(num);
        String provinceCode = body.getString("provCode");
        if (provinceCode == null) {
            return;
        }
        phoneRegLoc.setProvince(provinceCode);
        phoneRegLoc.setProvincename(body.getString("prov"));
        List<PosCityDTO> list = cityModuleRepository.queryCityAll(provinceCode);
        if (!CollectionUtils.isEmpty(list)) {
            final String cityName = body.getString("city");
            if (StringUtil.isBlank(cityName)) {
                PosCityDTO item = list.get(0);
                phoneRegLoc.setCity(item.getCode());
                phoneRegLoc.setCityname(item.getName());

            } else {
                Optional<PosCityDTO> optional = list.stream().filter(it ->
                        it.getName().replaceAll("市|县", "").contains(cityName.replaceAll("市|县", "")))
                        .findFirst();
                if (optional.isPresent()) {
                    PosCityDTO item = optional.get();
                    phoneRegLoc.setCity(item.getCode());
                    phoneRegLoc.setCityname(item.getName());
                }
            }
        }

        phoneRegLoc.setSuit(String.valueOf(suit));
        phoneRegLoc.setSupplier(body.getString("name"));
        int id = phoneRegLocMapper.insert(phoneRegLoc);
        System.out.println(id);
    }


}
